const userListEle = document.querySelector('#user-list') //tbody
const baseUrl = "http://47.105.173.95:3000/api/users"

/*-----------------------网络请求相关------------------------- */
function ajaxGet(url, callback) {
    //#1.创建xhr实例
    const xhr = new XMLHttpRequest()
    //#2.初始化一个请求
    xhr.open('GET', url)
    //#3.发送请求
    xhr.send()
    //#4.监听xhr的readystate的变化，使用onreadystatechange函数
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            const res = JSON.parse(xhr.responseText)
            if (typeof callback == 'function') {
                callback(res)
            }
        }
    }
};
//根据传入的参数获取用户数据
function getUsers(params,callback){
    const query = joinParams(params)
    const url = baseUrl + query
    ajaxGet(url, function (res) {
        //如果成功获取到用户数据，则回调
        if (res.code == 0) {
            const users = res.results.users
            callback(users)
        } else {
            //否则则弹出提示框
            alert(res.msg)
        }
    })
}

function joinParams(params){
    let  query = '?' 
    for(let key in params){
        query += `${key}=${params[key]}&`
    }
    return query.slice(0,-1)
}

/*-----------------设置用户列表相关-------------------- */
//初始化用户列表数据
(function initUsers() {
    getUsers({_page:1,_limit:20},function(users){
        renderUserList(users)
    })
})()
//把用户数据渲染到表格
function renderUserList(users) {
    const html = users.map(user => {
        return `
                <tr>
                    <th>${user.id}</th>
                    <th>${user.username}</th>
                    <th>${user.gender == 0 ? '男' : '女'}</th>
                    <th>${user.telephone}</th>
                    <th>${user.email}</th>
                    <th>
                        <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal-detail" data-id=${user.id} data-type="detail">详细</button>
                        <button type="button" class="btn btn-danger btn-sm" data-id=${user.id} data-type="delete">删除</button>
                    </th>
                </tr>`
    }).join('')
    userListEle.innerHTML = html
};
//给用户列表操作栏的按钮绑定事件
(function bindUserListButton() {
    userListEle.addEventListener('click', function (e) {
        const clickElement = e.target
        if (clickElement.tagName == 'BUTTON') {
            if (clickElement.dataset.type == 'detail') {
                //点击的是详细按钮
                const id = clickElement.dataset.id //获取点击的详细按钮对应的id
                getUsers({id:id}, function (users) {
                    setFormValue(detailFormOption, users[0])
                })
            } else if (clickElement.dataset.type == 'delete') {
                //删除操作
                //TODO
            }
        }
    });
})()


/*------------------用户详细表单相关---------------------- */
//表单配置文件
const detailFormOption = {
    id: {
        selector: '#id',//选择器
        dataKey: "id",//对应的返回数据中的键
    },
    username: {//字段名称
        selector: '#username',//选择器
        dataKey: "username",//对应的返回数据中的键
        element: null //输入框元素，由后面的initDetailFormElement函数获取并挂载到此处
    },
    email: {
        selector: '#email',
        dataKey: 'email'
    },
    nickname: {
        selector: "#nickname",
        dataKey: "nicheng"
    },
    telephone: {
        selector: '#telephone',
        dataKey: "telephone"
    },
    birthday: {
        selector: '#birthday',
        dataKey: "birthday"
    },
    gender: {
        selector: "[name=gender]",//checkbox和radio推荐使用name做为选择器
        dataKey: 'gender'
    },
    state: {
        selector: "#state",
        dataKey: 'state'
    },
    addr: {
        selector: "#addr",
        dataKey: 'address'
    },
    loginTime: {
        selector: "#login-time",
        dataKey: 'time'
    },
    intro: {
        selector: "#intro",
        dataKey: 'intro'
    },
    permission: {
        selector: "[name='permission']",
        dataKey: 'permission'
    }
};

//把所有字段对应的输入框找到并挂载到detailFormFieldElement里面
(function mountElementTodetailFormOption() {
    for (let field in detailFormOption) {
        const fieldObj = detailFormOption[field]
        const selector = fieldObj.selector
        const elements = document.querySelectorAll(selector)
        if (elements.length > 1) {
            fieldObj.element = [...elements]
        } else if (elements.length == 1) {
            fieldObj.element = elements[0]
        }
    }
})()

/*----------------------表单通用--------------------------- */
//设置表单的数据
function setFormValue(formOption, data) {
    for (let field in formOption) {
        const element = formOption[field].element
        const fieldKey = formOption[field].dataKey
        const fieldValue = data[fieldKey]
        if (element) {
            if (Array.isArray(element)) {
                if (element[0].type == "radio") {
                    element.forEach(item => {
                        if (item.value == fieldValue) {
                            item.checked = true
                        }
                    })
                } else if (element[0].type == 'checkbox') {
                    //TODO checkbox
                    const valueList = fieldValue.split(',')
                    element.forEach(item => {
                        if (valueList.includes(item.value)) {
                            item.checked = true
                        }
                    })
                }
            } else {
                element.value = fieldValue
            }
        }
    }
}
/*-------------------------分页相关----------------------------------- */
const paginationEle = document.querySelector('.pagination');
(function bindPagination(){
    paginationEle.onclick = function(e){
        //阻止事件默认行为
        e.preventDefault();
        const clickElement = e.target
        const page = clickElement.dataset.page
        //根据页面和每页的数量请求页码对应的用户数据
        getUsers({_page:page,_limit:20},function(users){
            renderUserList(users)
            pageActive(page)
        })
        //把数据渲染到页面
    }
})()
//激活当且页码
function pageActive(page){
    const pageLis = paginationEle.querySelectorAll('li')
    console.log(pageLis)
    pageLis.forEach(li => {
        if(li.dataset.page == page){
            li.classList.add('active')
        }else{
            li.classList.remove('active')
        }
    })

}


/*
 触发点击事件 -> 请求数据 -> 拿到返回的数据并解析 -> 渲染到网页
*/